﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>供应商新增</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px 0;
            background-color: #f5f7fa;
            min-height: 100vh;
            box-sizing: border-box;
        }

        .container {
            padding: 0 20px;
            max-width: 1200px;
            margin: 0 auto;
            width: 100%;
            box-sizing: border-box;
        }

        .form-section {
            background: #fff;
            padding: 25px;
            margin-bottom: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

            .form-section h3 {
                margin-top: 0;
                margin-bottom: 20px;
                color: #333;
                font-size: 16px;
                border-left: 3px solid #409eff;
                padding-left: 10px;
                font-weight: 500;
            }

        .el-row {
            margin-bottom: 18px;
        }

        .saveBlock {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #fff;
            padding: 15px 20px;
            border-top: 1px solid #eee;
            z-index: 999;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
        }

        .btnBlock {
            text-align: right;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            box-sizing: border-box;
        }

        .required-mark {
            color: #f56c6c;
            margin-right: 4px;
        }

        .error-tip {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 5px;
        }

        @@media (max-width: 768px) {
            .container {
                padding: 0 15px;
            }

            .form-section {
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 基础信息表单 -->
        <div class="form-section">
            <h3>基础信息</h3>
            <el-form ref="basicForm" :model="formData" :rules="basicRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="供应商编码" prop="supplierCode">
                            <el-input v-model="formData.supplierCode" placeholder="自动生成" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商名称" prop="supplierName">
                            <el-input v-model.trim="formData.supplierName" placeholder="请输入供应商名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="所属行业" prop="industry">
                            <el-select v-model="formData.industry" placeholder="请选择" clearable>
                                <el-option v-for="item in industryList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商分类" prop="supplierType">
                            <el-select v-model="formData.supplierType" placeholder="请选择" clearable>
                                <el-option v-for="item in typeList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系人" prop="contactPerson">
                            <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="contactPhone">
                            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="电子邮箱" prop="email">
                            <el-input v-model="formData.email" placeholder="请输入电子邮箱"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="*进货部门" prop="purchaseDept">
                            <el-select v-model="formData.purchaseDept" placeholder="请选择部门" clearable @@change="loadUserByDept">
                                <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="*进货负责人" prop="purchaseManager">
                            <el-select v-model="formData.purchaseManager"
                                       placeholder="请选择负责人"
                                       clearable
                                       @@change="handleManagerChange">
                                <!-- 关键：value 转为 Number 类型 -->
                                <el-option v-for="user in userList"
                                           :key="user.id"
                                           :label="user.name"
                                           :value="user.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="*状态" prop="status">
                            <el-radio-group v-model="formData.status">
                                <el-radio v-for="item in statusList" :key="item.code" :label="Number(item.code)" border>{{ item.name }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="供应商地址" prop="address">
                            <el-input v-model="formData.address" placeholder="请输入供应商详细地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 财务信息表单 -->
        <div class="form-section">
            <h3>财务信息</h3>
            <el-form ref="financeForm" :model="formData.finance" :rules="financeRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账户名称" prop="accountName">
                            <el-input v-model="formData.finance.accountName" placeholder="请输入开户账户名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" prop="taxNo">
                            <el-input v-model="formData.finance.taxNo" placeholder="请输入18位纳税人识别号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="银行账号" prop="bankAccount">
                            <el-input v-model="formData.finance.bankAccount" placeholder="请输入银行账号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" prop="bankName">
                            <el-input v-model="formData.finance.bankName" placeholder="请输入开户银行名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="银行地址" prop="bankAddress">
                            <el-input v-model="formData.finance.bankAddress" placeholder="请输入开户行详细地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 附件上传 -->
        <div class="form-section">
            <h3>上传附件</h3>
            <el-upload ref="upload"
                       v-model:file-list="fileList"
                       action=""
                       :auto-upload="false"
                       :on-change="handleFileChange"
                       :limit="5"
                       accept=".doc,.docx,.pdf,.rar,.zip"
                       list-type="text">
                <el-button type="primary" :loading="uploadLoading">上传</el-button>
                <div class="el-upload__text">
                    您可以上传doc、pdf、rar等格式的文件，单个文件最大200MB
                </div>
            </el-upload>
        </div>

        <!-- 按钮栏 -->
        <div class="saveBlock">
            <div class="btnBlock">
                <el-button @@click="handleClose" :loading="buttonLoading.close">关闭</el-button>
                &nbsp;&nbsp;
                <el-button type="success" @@click="handleSaveAndAdd" :loading="buttonLoading.saveAndAdd">保存并新增</el-button>
                &nbsp;&nbsp;
                <el-button type="primary" @@click="handleSave" :loading="buttonLoading.save">保存</el-button>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted, toRaw } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            setup() {
                // 表单数据
                const formData = reactive({
                    supplierCode: '',
                    supplierName: '',
                    industry: '',
                    supplierType: '',
                    contactPerson: '',
                    contactPhone: '',
                    email: '',
                    purchaseDept: null,
                    purchaseManager: null,
                    status: null,
                    address: '',
                    remark: '',
                    finance: {
                        accountName: '',
                        taxNo: '',
                        bankAccount: '',
                        bankName: '',
                        bankAddress: ''
                    }
                });

                // 附件列表
                const fileList = ref([]);
                const uploadLoading = ref(false);

                // 核心数据
                const industryList = ref([]);
                const typeList = ref([]);
                const deptList = ref([]);
                const userList = ref([]);
                const statusList = ref([]);

                // 表单引用
                const basicForm = ref(null);
                const financeForm = ref(null);

                // 按钮加载状态
                const buttonLoading = reactive({
                    close: false,
                    save: false,
                    saveAndAdd: false
                });

                // 基础表单验证规则
                const basicRules = {
                    supplierName: [{ required: true, message: '请输入供应商名称', trigger: ['blur', 'change'] }],
                    purchaseDept: [{ required: true, message: '请选择进货部门', trigger: ['blur', 'change'] }],
                    purchaseManager: [{ required: true, message: '请选择进货负责人', trigger: ['blur', 'change'] }],
                    status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }]
                };

                // 财务表单验证规则
                const financeRules = {
                    taxNo: [{ pattern: /^\d{18}$/, message: '纳税人识别号为18位数字', trigger: 'blur', required: false }]
                };

                // 加载字典数据
                const loadDictData = async () => {
                    try {
                        const [industryRes, typeRes, statusRes] = await Promise.all([
                            axios.get('/BiSupplier/GetDictData?type=supplier_industry'),
                            axios.get('/BiSupplier/GetDictData?type=supplier_type'),
                            axios.get('/BiSupplier/GetDictData?type=supplier_status')
                        ]);

                        industryList.value = industryRes.data.data || [];
                        typeList.value = typeRes.data.data || [];
                        statusList.value = statusRes.data.data || [];

                        // 设置默认状态
                        if (statusList.value.length > 0) {
                            formData.status = Number(statusList.value[0].code);
                        } else {
                            formData.status = 1;
                        }
                    } catch (error) {
                        ElMessage.error(`字典数据加载异常：${error.message}`);
                        industryList.value = [];
                        typeList.value = [];
                        statusList.value = [];
                        formData.status = 1;
                    }
                };

                // 根据部门ID加载用户（增强错误处理）
                const loadUserByDept = async (orgId) => {
                    console.log('前端传入的部门ID:', orgId);

                    try {
                        if (!orgId) {
                            userList.value = [];
                            formData.purchaseManager = null;
                            return;
                        }

                        const res = await axios.get(`/BiSupplier/GetUsers?orgId=${orgId}`);
                        console.log('后端返回的用户数据:', res.data);

                        if (res.data && res.data.code === 200) {
                            userList.value = res.data.data || [];
                            console.log('前端渲染的用户列表:', userList.value);

                            if (userList.value.length === 0) {
                                ElMessage.warning('该部门下暂无用户');
                            }
                        } else {
                            // 即使后端返回错误，也设置空列表避免界面卡住
                            userList.value = [];
                            ElMessage.warning(res.data?.msg || '加载用户失败，已清空选项');
                        }
                    } catch (error) {
                        console.error('加载用户错误:', error);
                        // 出错时设置空列表，确保界面可用
                        userList.value = [];
                        ElMessage.error('加载用户失败，请检查网络连接');
                    }
                };
                // 加载部门和用户数据
                const loadDeptAndUser = async () => {
                    try {
                        const [deptRes, userRes] = await Promise.all([
                            axios.get('/BiSupplier/GetOrgTree'),
                            axios.get('/BiSupplier/GetUsers')
                        ]);

                        // 处理部门数据
                        const flattenDeptList = (treeNodes) => {
                            const result = [];
                            const flatten = (nodes) => {
                                if (!nodes || !Array.isArray(nodes)) return;
                                nodes.forEach(node => {
                                    if (node) {
                                        result.push({
                                            id: node.id || node.orgId || node.value,
                                            name: node.label || node.orgName || node.name
                                        });
                                        if (node.children && node.children.length > 0) {
                                            flatten(node.children);
                                        }
                                    }
                                });
                            };
                            flatten(deptRes.data.data || []);
                            return result;
                        };

                        deptList.value = flattenDeptList(deptRes.data.data || []);
                        userList.value = userRes.data.data || [];
                    } catch (error) {
                        ElMessage.error(`部门/用户数据加载异常：${error.message}`);
                        deptList.value = [];
                        userList.value = [];
                    }
                };

                // 生成供应商编码
                const generateSupplierCode = async () => {
                    try {
                        const res = await axios.get('/BiSupplier/GetPreviewCode');
                        if (res.data.success && res.data.code) {
                            formData.supplierCode = res.data.code;
                        } else {
                            formData.supplierCode = 'SUP' + new Date().getTime();
                        }
                    } catch (error) {
                        formData.supplierCode = 'SUP' + new Date().getTime();
                    }
                };

                // 初始化表单
                const initForm = async () => {
                    try {
                        // 尝试加载本地草稿
                        const localDraft = localStorage.getItem('supplierDraft');
                        if (localDraft) {
                            const draft = JSON.parse(localDraft);
                            Object.assign(formData, draft.formData);
                            fileList.value = draft.fileList || [];
                            ElMessage.success('已加载上次保存的草稿数据');
                            return;
                        }

                        // 无草稿则生成新编码
                        await generateSupplierCode();
                    } catch (error) {
                        await generateSupplierCode();
                    }
                };

                // 负责人选择变化处理
                const handleManagerChange = (userId) => {
                    if (userId) {
                        const selectedUser = userList.value.find(user => user.id === userId);
                        if (selectedUser) {
                            formData.purchaseDept = selectedUser.orgId;
                        }
                    }
                };

                // 加载部门树（用于渲染部门选择框）
                const loadDeptTree = async () => {
                    try {
                        const res = await axios.get('/BiSupplier/GetOrgTree');
                        console.log('部门树原始数据:', res.data);

                        // 简化部门数据处理
                        const flattenDept = (nodes) => {
                            const result = [];
                            const traverse = (node, level = 0) => {
                                if (!node) return;

                                // 确保有有效的id和name
                                const deptId = node.id || node.orgId || node.value;
                                const deptName = node.label || node.orgName || node.name;

                                if (deptId && deptName) {
                                    result.push({
                                        id: Number(deptId),
                                        name: deptName,
                                        level: level
                                    });
                                }

                                // 递归处理子节点
                                if (node.children && Array.isArray(node.children)) {
                                    node.children.forEach(child => traverse(child, level + 1));
                                }
                            };

                            // 处理根节点
                            if (Array.isArray(nodes)) {
                                nodes.forEach(root => traverse(root));
                            }
                            return result;
                        };

                        deptList.value = flattenDept(res.data.data || []);
                        console.log('处理后的部门列表:', deptList.value);

                    } catch (error) {
                        console.error('加载部门数据失败:', error);
                        ElMessage.error(`部门数据加载失败：${error.message}`);
                        deptList.value = [];
                    }
                };

                // 测试用户数据（移到 loadDeptTree 外部）
                const testUserData = async () => {
                    try {
                        console.log('开始测试用户数据...');

                        // 测试获取所有用户
                        const allUsersRes = await axios.get('/BiSupplier/GetUsers');
                        console.log('所有用户数据:', allUsersRes.data);

                        // 测试按部门获取用户
                        if (deptList.value.length > 0) {
                            const testDeptId = deptList.value[0].id;
                            const deptUsersRes = await axios.get(`/BiSupplier/GetUsers?orgId=${testDeptId}`);
                            console.log(`部门 ${testDeptId} 的用户数据:`, deptUsersRes.data);
                        }

                    } catch (error) {
                        console.error('测试用户数据失败:', error);
                    }
                };

                // 附件处理
                const handleFileChange = (file, fileList) => {
                    if (file.size > 200 * 1024 * 1024) {
                        ElMessage.error('文件大小不能超过200MB');
                        fileList.value = fileList.value.filter(f => f.uid !== file.uid);
                    }
                };

                // 关闭按钮
                const handleClose = () => {
                    buttonLoading.close = true;
                    window.history.back();
                };

                // 保存草稿
                const handleSave = async () => {
                    // 验证核心字段
                    const requiredFields = [
                        { name: '供应商名称', value: formData.supplierName, valid: formData.supplierName && formData.supplierName.trim().length > 0 },
                        { name: '进货部门', value: formData.purchaseDept, valid: formData.purchaseDept !== null && formData.purchaseDept !== undefined },
                        { name: '进货负责人', value: formData.purchaseManager, valid: formData.purchaseManager !== null && formData.purchaseManager !== undefined },
                        { name: '状态', value: formData.status, valid: formData.status !== null && formData.status !== undefined }
                    ];

                    const missingFields = requiredFields.filter(field => !field.valid).map(field => field.name);

                    if (missingFields.length > 0) {
                        ElMessage.warning(`请完善以下信息：${missingFields.join('、')}`);
                        return;
                    }

                    buttonLoading.save = true;

                    try {
                        const draftData = {
                            formData: toRaw(formData),
                            fileList: fileList.value.map(f => ({ name: f.name, url: f.url })),
                            saveTime: new Date().toLocaleString()
                        };
                        localStorage.setItem('supplierDraft', JSON.stringify(draftData));
                        ElMessage.success('草稿保存成功！');
                    } catch (error) {
                        ElMessage.error('保存失败，请重试');
                    } finally {
                        buttonLoading.save = false;
                    }
                };

                // 保存并新增
                const handleSaveAndAdd = async () => {
                    // 验证核心字段
                    const requiredFields = [
                        { name: '供应商名称', value: formData.supplierName, valid: formData.supplierName && formData.supplierName.trim().length > 0 },
                        { name: '进货部门', value: formData.purchaseDept, valid: formData.purchaseDept !== null && formData.purchaseDept !== undefined },
                        { name: '进货负责人', value: formData.purchaseManager, valid: formData.purchaseManager !== null && formData.purchaseManager !== undefined },
                        { name: '状态', value: formData.status, valid: formData.status !== null && formData.status !== undefined }
                    ];

                    const missingFields = requiredFields.filter(field => !field.valid).map(field => field.name);

                    if (missingFields.length > 0) {
                        ElMessage.warning(`请完善以下信息：${missingFields.join('、')}`);
                        return;
                    }

                    buttonLoading.saveAndAdd = true;

                    try {
                        // 构建提交数据
                        const submitData = {
                            SupplierCode: formData.supplierCode,
                            SupplierName: formData.supplierName.trim(),
                            Industry: formData.industry ? Number(formData.industry) : 1,
                            CustomerSource: formData.supplierType ? Number(formData.supplierType) : 1,
                            ContactPerson: formData.contactPerson || "",
                            ContactPhone: formData.contactPhone || "",
                            Email: formData.email || "",
                            Address: formData.address || "",
                            CustomerId: formData.purchaseDept ? Number(formData.purchaseDept) : null,
                            PurchaseManagerId: formData.purchaseManager ? Number(formData.purchaseManager) : null,
                            Status: formData.status ? formData.status.toString() : "1",
                            AccountName: formData.finance.accountName || "",
                            TaxpayerId: formData.finance.taxNo || "",
                            BankAccount: formData.finance.bankAccount || "",
                            OpeningBank: formData.finance.bankName || "",
                            BankAddress: formData.finance.bankAddress || "",
                            Remarks: formData.remark || "",
                            AttachmentId: 0,
                            IsDelete: "0",
                            CreateBy: "system",
                            CreateTime: new Date().toISOString(),
                            UpdateBy: "system",
                            UpdateTime: new Date().toISOString()
                        };

                        console.log('提交的数据:', submitData); // 调试信息

                        const res = await axios.post('/BiSupplier/Create', submitData);

                        if (res.data.code === 200) {
                            ElMessage.success('保存成功！');
                            localStorage.removeItem('supplierDraft');
                            await resetForm();
                        } else {
                            ElMessage.error(res.data.msg || '保存失败');
                        }
                    } catch (error) {
                        console.error('保存错误:', error);
                        if (error.response) {
                            const responseData = error.response.data;
                            ElMessage.error(responseData.msg || '请求失败');
                        } else if (error.request) {
                            ElMessage.error('网络错误，请检查网络连接');
                        } else {
                            ElMessage.error(`请求配置错误: ${error.message}`);
                        }
                    } finally {
                        buttonLoading.saveAndAdd = false;
                    }
                };

                // 重置表单方法
                const resetForm = async () => {
                    const currentCode = formData.supplierCode;

                    Object.assign(formData, {
                        supplierName: '',
                        industry: '',
                        supplierType: '',
                        contactPerson: '',
                        contactPhone: '',
                        email: '',
                        purchaseDept: null,
                        purchaseManager: null,
                        address: '',
                        remark: '',
                        finance: {
                            accountName: '',
                            taxNo: '',
                            bankAccount: '',
                            bankName: '',
                            bankAddress: ''
                        }
                    });

                    // 设置默认状态
                    if (statusList.value && statusList.value.length > 0) {
                        formData.status = Number(statusList.value[0].code);
                    } else {
                        formData.status = 1;
                    }

                    formData.supplierCode = currentCode;
                    fileList.value = [];

                    // 清除验证状态
                    basicForm.value?.clearValidate();
                    financeForm.value?.clearValidate();

                    // 重新生成编码
                    await generateSupplierCode();

                    ElMessage.info('表单已重置，可以添加下一条记录');
                };

                // 页面初始化
                onMounted(async () => {
                    try {
                        await loadDictData();
                        await loadDeptAndUser();
                        await loadDeptTree();
                        await testUserData();
                        await initForm();

                        // 清除验证状态
                        setTimeout(() => {
                            if (basicForm.value) basicForm.value.clearValidate();
                        }, 1000);
                    } catch (error) {
                        ElMessage.error('页面加载失败，请刷新重试');
                    }
                });

                return {
                    formData,
                    fileList,
                    uploadLoading,
                    industryList,
                    typeList,
                    deptList,
                    userList,
                    statusList,
                    basicForm,
                    financeForm,
                    buttonLoading,
                    basicRules,
                    financeRules,
                    handleClose,
                    handleSave,
                    handleSaveAndAdd,
                    handleFileChange,
                    loadUserByDept,
                    handleManagerChange,

                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>